package utils;

import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 *
 * @author ZimmE
 */
@Startup
@Singleton
@LocalBean
public class FileLogger implements UncaughtExceptionHandler {

    private static final Logger applicationLogger = Logger.getLogger("MyGrona");
    private static final Logger errorLogger = Logger.getLogger("MyGrona.error");

    public FileLogger() {
        try {
            FileHandler fh = new FileHandler("MyGrona.log", true);
            applicationLogger.addHandler(fh);
            applicationLogger.setLevel(Level.ALL);
            fh = new FileHandler("MyGrona.err.log", true);
            errorLogger.addHandler(fh);
            errorLogger.setLevel(Level.ALL);
            Logger.getLogger(FileLogger.class.getName()).log(Level.INFO, "Log files created.");
        } catch (IOException ex) {
            Logger.getLogger(FileLogger.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(FileLogger.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(FileLogger.class.getName()).log(Level.SEVERE, null, ex);
        }
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        errorLogger.log(Level.SEVERE, null, e);
    }
}
